import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login as apiLogin } from '@/services/api'

export const useAuthStore = defineStore('auth', () => {
  const user = ref<{
    account: string
    nickname: string
    token: string
  } | null>(null)

  // 初始化时从本地存储加载
  const initFromStorage = () => {
    const stored = localStorage.getItem('auth')
    if (stored) {
      user.value = JSON.parse(stored)
    }
  }

  // 登录方法
  const login = async (account: string, password: string) => {
    const auth = await apiLogin({ account, password })
    user.value = {
      account: auth.userInfo.account,
      nickname: auth.userInfo.nickname,
      token: auth.token,
    }
    // 保存到本地存储
    localStorage.setItem('auth', JSON.stringify(user.value))
  }

  // 登出方法
  const logout = () => {
    user.value = null
    localStorage.removeItem('auth')
  }

  // 检查是否已登录
  const isAuthenticated = () => {
    return !!user.value
  }

  // 初始化
  initFromStorage()

  return { user, login, logout, isAuthenticated }
})
